package info.batcloud.fanli.api.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import info.batcloud.fanli.core.alipay.domain.NotifyParam;
import info.batcloud.fanli.core.service.OrderService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class AlipayController {

    @Inject
    private OrderService orderService;

    @PostMapping("/callback")
    public Object callback(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {
        Map<String, String> result = new HashMap<>();
        for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            result.put(entry.getKey().trim(), entry.getValue()[0].trim());
        }
        String jsonString = JSON.toJSONString(result);

        NotifyParam param = JSON.parseObject(jsonString, NotifyParam.class);
        param.setRawMap(result);
        boolean flag = orderService.handleAlipayNotify(param);
        response.getWriter().write(flag ? "success" : "failure");
        response.flushBuffer();

        return null;
    }

}
